package com.tdu.spider.biz.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ImageUtil {

    public static String zipWidthHeightImageFile(File oldFile, File newFile) {
        return zipWidthHeightImageFile(oldFile, newFile, null, null);
    }

    /**
     * 按设置的宽度高度压缩图片文件<br> 先保存原文件，再压缩、上传
     * @param oldFile  要进行压缩的文件全路径
     * @param newFile  新文件
     * @param width  宽度
     * @param height 高度
     * @return 返回压缩后的文件的全路径
     */
    public static String zipWidthHeightImageFile(File oldFile, File newFile, Integer width,
                                                 Integer height) {
        if (oldFile == null) {
            return null;
        }
        String newImage = null;
        try {
            BufferedImage sourceImg = ImageIO.read(new FileInputStream(oldFile));
            if (width == null && height == null) {
                int _width = sourceImg.getWidth();
                int _height = sourceImg.getHeight();
                double bili = 0;
                if (_width > 1080) {
                    bili = 1080/Double.valueOf(_width) ;
                    width = (int) Math.round(_width * bili);
                    height = (int) Math.round(_height * bili);
                }
            }
            String srcImgPath = newFile.getAbsoluteFile().toString();
            String subfix = "jpg";
            subfix = srcImgPath.substring(srcImgPath.lastIndexOf(".") + 1, srcImgPath.length());

            BufferedImage buffImg = null;
            if (subfix.equals("png")) {
                buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            } else {
                buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            }

            Graphics2D graphics = buffImg.createGraphics();
            graphics.setBackground(new Color(255, 255, 255));
            graphics.setColor(new Color(255, 255, 255));
            graphics.fillRect(0, 0, width, height);
            graphics.drawImage(sourceImg.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0,
                null);

            ImageIO.write(buffImg, subfix, new File(srcImgPath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newImage;
    }
//
//    public static void main(String[] args) {
//        zipWidthHeightImageFile(
//            new File("/Users/tangdu/Downloads/2e6f8b9ae3b2cb3ccc326df7aec3c1a0.jpeg"),
//            new File("/Users/tangdu/Downloads/123.jpeg"));
//    }
}
